<template>
  <div :style="styleObj">
    <v-chart ref="myVChart" :option="options" autoresize />
  </div>
</template>

<script>
// 移除注释行，保留实际代码
import { targetWidgetLinkageLogic } from "@/views/bigscreenDesigner/designer/linkageLogic";

// 移除全局变量per

export default {
  name: "widgetLiquidFill",
  props: {
    value: Object,
    ispreview: Boolean,
    widgetIndex: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      options: {
        series: [
          {
            type: "liquidFill",
            data: [{ value: 0.6 }], // 默认值
            radius: "80%",
            outline: {
              show: true,
              borderDistance: 10,
              itemStyle: {
                color: "#fff",
                borderColor: "#5CACEE",
                borderWidth: 10,
                shadowBlur: 10,
              },
            },
            label: {
              // 使用默认值替代不存在的per变量
              text: "{nums|0.6}{percent|%}",
              color: "#003092",
              insideColor: "#fff",
              fontSize: 50,
              fontFamily: "sans-serif",
              fontStyle: "normal",
              fontWeight: "normal",
            },
            backgroundStyle: {
              color: "#fff",
              borderColor: "#5CACEE",
              borderWidth: 10,
            },
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: "#5CACEE" },
                  { offset: 1, color: "#3066BE" },
                ],
                global: false,
              },
              shadowBlur: 10,
              shadowColor: "rgba(92, 172, 238, 0.8)",
            },
            emphasis: {
              itemStyle: {
                opacity: 1,
              },
            },
            animationDuration: 1500,
            animationEasing: "cubicInOut",
            amplitude: 20,
            waveLength: 300,
            direction: "right",
            waveAnimation: true,
          },
        ],
      },
      optionsStyle: {},
      optionsData: {},
      optionsCollapse: {},
      optionsSetup: {},
      flagInter: null,
    };
  },
  computed: {
    styleObj() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.optionsStyle.width ? this.optionsStyle.width + "px" : "200px",
        height: this.optionsStyle.height ? this.optionsStyle.height + "px" : "200px",
        left: this.optionsStyle.left + "px",
        top: this.optionsStyle.top + "px",
        background: this.optionsSetup.background,
      };
    },
    allComponentLinkage() {
      return this.$store.state.designer.allComponentLinkage;
    },
  },
  watch: {
    value: {
      handler(val) {
        if (!val) return;
        this.optionsStyle = val.position || {};
        this.optionsData = val.data || {};
        this.optionsCollapse = val.collapse || {};
        this.optionsSetup = val.setup || {};
        this.editorOptions();
      },
      deep: true,
    },
    // 添加对ispreview变化的监听，确保预览模式下数据正确更新
    ispreview: {
      handler(newVal) {
        if (newVal) {
          this.setOptionsData();
          // 强制更新一次标签
          this.setOptionsLabel();
        }
      }
    }
  },
  created() {
    if (this.value) {
      this.optionsStyle = this.value.position || {};
      this.optionsData = this.value.data || {};
      this.optionsCollapse = this.value.collapse || {};
      this.optionsSetup = this.value.setup || {};
      this.editorOptions();
    }
  },
  mounted() {
    targetWidgetLinkageLogic(this);
    // 组件挂载后立即检查数据并更新，特别是在预览模式下
    if (this.ispreview) {
      this.$nextTick(() => {
        this.setOptionsData();
        this.setOptionsLabel();
      });
    }
  },
  methods: {
    editorOptions() {
      // 先设置数据相关的配置
      this.setOptionsStyle();
      this.setOptionsData();
      // 然后设置显示相关的配置
      this.setOptionsLabel();
      this.setOptionsOutLine();
      this.setOptionsBackground();
      this.setOptionsGradient();
      this.setOptionsOther();
    },
    
    // 添加这个方法来确保样式配置正确
    setOptionsStyle() {
      if (!this.optionsStyle.width) this.optionsStyle.width = 200;
      if (!this.optionsStyle.height) this.optionsStyle.height = 200;
      if (!this.optionsStyle.left) this.optionsStyle.left = 0;
      if (!this.optionsStyle.top) this.optionsStyle.top = 0;
    },

    setOptionsLabel() {
      const optionsSetup = this.optionsSetup;
      const currentValue = this.options.series[0].data[0].value;
      const label = {
        show: optionsSetup.isShowTitle !== false, // 默认显示
        text: "{nums|" + currentValue + "}{percent|%}",
        color: optionsSetup.waveOutTextNumColor || "#003092",
        insideColor: optionsSetup.waveInTextNumColor || "#fff",
        fontWeight: optionsSetup.textNumFontWeight || "normal",
        fontSize: optionsSetup.textNumFontSize || 50,
        fontFamily: optionsSetup.textNumFontFamily || "sans-serif",
        fontStyle: optionsSetup.textNumFontStyle || "normal",
      };
      this.options.series[0].label = label;
    },

    setOptionsOutLine() {
      const optionsSetup = this.optionsSetup;
      const outline = {
        show: optionsSetup.isShowOuterBorder !== false, // 默认显示
        borderDistance: optionsSetup.innerSpacing || 10,
        itemStyle: {
          color: optionsSetup.innerSpacingColor || "#fff",
          borderColor: optionsSetup.outBorderColor || "#5CACEE",
          borderWidth: optionsSetup.outWidth || 10,
          shadowBlur: optionsSetup.outShadow || 10,
        },
      };
      this.options.series[0].outline = outline;
    },

    setOptionsBackground() {
      const optionsSetup = this.optionsSetup;
      const backgroundStyle = {
        color: optionsSetup.backColor || "#fff",
        borderColor: optionsSetup.innerBorderColor || "#5CACEE",
        borderWidth: optionsSetup.innerBorderWidth || 10,
      };
      this.options.series[0].backgroundStyle = backgroundStyle;
    },

    setOptionsGradient() {
      const optionsSetup = this.optionsSetup;
      const colorStops = [
        {
          offset: 0,
          color: optionsSetup.color0Start || "#5CACEE",
        },
        {
          offset: 1,
          color: optionsSetup.color100End || "#3066BE",
        },
      ];
      this.options.series[0].itemStyle.color.colorStops = colorStops;
    },

    setOptionsOther() {
      const os = this.optionsSetup;
      const isWaveScroll = os.isWaveScroll !== false; // 默认滚动
      this.options.series[0].amplitude = os.waveFluctuate || 20;
      this.options.series[0].waveLength = os.waveNumber || 300;
      this.options.series[0].direction = os.waveDirection || "right";
      this.options.series[0].waveAnimation = isWaveScroll;
    },

    setOptionsData() {
      const optionsData = this.optionsData;
      if (!optionsData) return;
      
      // 确保动态数据对象存在
      optionsData.dynamicData = optionsData.dynamicData || {};
      
      // 清除之前的定时器
      clearInterval(this.flagInter);
      
      // 根据数据类型处理
      if (optionsData.dataType === "staticData" && optionsData.staticData) {
        this.staticDataFn(optionsData.staticData);
      } else if (optionsData.dynamicData) {
        this.dynamicDataFn(optionsData.dynamicData, optionsData.refreshTime || 5000);
      } else if (this.optionsSetup && typeof this.optionsSetup.defaultValue !== 'undefined') {
        // 如果有默认值设置，则使用默认值
        this.options.series[0].data[0].value = this.optionsSetup.defaultValue;
        this.setOptionsLabel();
      }
    },

    staticDataFn(val) {
      try {
        // 处理可能是字符串的数据
        const staticData = typeof val === "string" ? JSON.parse(val) : val;
        if (staticData && staticData[0] && typeof staticData[0].value !== "undefined") {
          const value = staticData[0].value;
          this.options.series[0].data[0].value = value;
          // 立即更新标签
          this.setOptionsLabel();
        }
      } catch (error) {
        console.error("静态数据解析错误:", error);
      }
    },

    dynamicDataFn(val, refreshTime) {
      if (!val) return;
      
      // 立即获取一次数据
      this.getEchartData(val);
      
      // 预览模式下设置定时器
      if (this.ispreview) {
        this.flagInter = setInterval(() => {
          this.getEchartData(val);
        }, refreshTime);
      }
    },

    getEchartData(val) {
      try {
        // 检查组件是否已销毁
        if (this._isDestroyed) return;
        
        // 使用mixins中的queryEchartsData方法
        const data = this.queryEchartsData(val);
        data.then((res) => {
          if (res && res.length > 0 && typeof res[0].value !== "undefined") {
            // 更新数据值
            this.options.series[0].data[0].value = res[0].value;
            // 同步更新标签
            this.setOptionsLabel();
          }
        }).catch(error => {
          console.error("获取动态数据失败:", error);
        });
      } catch (error) {
        console.error("获取数据异常:", error);
      }
    },
  },
};
</script>
<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>